package com.zhoust.controller.interceptor;

import com.zhoust.utils.IMOOCJSONResult;
import com.zhoust.utils.JsonUtils;
import com.zhoust.utils.RedisOperator;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 15703
 * @version 1.0
 * @Title
 * @package com.zhoust.controller.interceptor
 * @date 2020/10/19 16:30
 * @desc
 */
public class UserTokenInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisOperator redisOperator;

    /**
     * 在请求到达controller之前拦截
     * @param request
     * @param response
     * @param handler
     * @return true 验证通过，false 验证失败
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");

        if(StringUtils.isNotBlank(userId)&&StringUtils.isNoneBlank(userToken)){
            String redisUserToken = redisOperator.get("user_token:" + userId);

            if(StringUtils.isBlank(redisUserToken)){
                returnJsonResponse("请先登录",response);
                return false;
            }else{
                if(userToken.equals(redisUserToken)){
                    return true;
                }else{
                    returnJsonResponse("异地登录了，请重新登录！",response);
                    return false;
                }
            }
        }else{
            returnJsonResponse("登录信息失效",response);
            return false;
        }
    }


    private void returnJsonResponse(String msg,HttpServletResponse response){
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/json");
            outputStream = response.getOutputStream();
            outputStream.write(JsonUtils.objectToJson(IMOOCJSONResult.errorMsg(msg)).getBytes("UTF-8"));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 访问controller之后，渲染视图之前
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 所有动作完成后
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
